# -*- coding: utf-8 -*-
import json
from time import sleep
import logging

import requests


class WorkFlowExec():
    def __init__(self, login_url, headers):
        self.headers = headers
        self.session = requests.Session()
        self.login_url = login_url
        self.user = 'admin'
        self.password = 'dolphinscheduler123'
        self.headers["token"] = "a01a0f0d78599ed8f66e905c9b703553"

        login_data = {
            'userName': self.user,
            'userPassword': self.password
        }
        try:
            response = self.session.post(self.login_url, headers=self.headers, data=login_data)
            res = json.loads(response.text)
            session_id = res["data"]["sessionId"]
            self.headers["sessionId"] = session_id
            self.logger = logging.getLogger('WorkFlowExec')
            self.logger.setLevel(logging.DEBUG)
        except Exception as e:
            print("服务器链接失败 ".format(e))

    def send_request(self, url, method='GET', params=None, json_data=None):
        """
        发送 HTTP 请求
        :param url: 请求的 URL
        :param method: 请求方法，默认为 GET
        :param params: 请求参数，如果 method 为 GET，则使用 params；如果为 POST，则使用 data
        :param json_data: JSON 格式的请求体，如果 method 为 POST，则使用 json
        :return: 请求响应
        """
        method = method.upper()
        if method not in ['GET', 'POST', 'PUT', 'DELETE']:
            raise ValueError('Unsupported HTTP method: {}'.format(method))

        print('Sending {} request to {} , params {}, json_data {}'.format(method, url, params, json_data))

        # 根据请求方法选择对应的方法发送请求
        if method == 'GET':
            response = requests.get(url, headers=self.headers, params=params)
        elif method == 'POST':
            if json_data:
                response = requests.post(url, headers=self.headers, params=params, json=json_data)
            else:
                response = requests.post(url, headers=self.headers, data=params)
        elif method == 'PUT':
            if json_data:
                response = requests.put(url, headers=self.headers, params=params, json=json_data)
            else:
                response = requests.put(url, headers=self.headers, data=params)
        elif method == 'DELETE':
            response = requests.delete(url, headers=self.headers, params=params)

        #self.logger.debug('Received response with status code: {}'.format(response.status_code))

        return response


if __name__ == '__main__':
    l = WorkFlowExec()
    l.login()
    # l.run()
    # a = l.red_init_data()
    # print(a)
